package com.example.deepai.service;

import com.example.deepai.model.ChatMessage;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class DeepSeekService {

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build();

    private final ObjectMapper objectMapper = new ObjectMapper();

    public String getCompletion(String userMessage, List<ChatMessage> history) throws IOException {
        log.info("开始处理用户消息: {}", userMessage);
        log.info("历史消息数量: {}", history.size());
        
        ObjectNode requestBody = objectMapper.createObjectNode();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("temperature", 0.7);

        ArrayNode messagesArray = requestBody.putArray("messages");

        // 添加历史消息，但限制数量以避免请求过大
        int historyLimit = Math.min(history.size(), 10);
        for (int i = Math.max(0, history.size() - historyLimit); i < history.size(); i++) {
            ChatMessage message = history.get(i);
            // 跳过最后一条消息，因为它就是当前的用户消息
            if (i == history.size() - 1 && message.getContent().equals(userMessage)) {
                continue;
            }
            ObjectNode messageNode = messagesArray.addObject();
            messageNode.put("role", message.getRole());
            messageNode.put("content", message.getContent());
        }

        // 添加用户当前消息
        ObjectNode userMessageNode = messagesArray.addObject();
        userMessageNode.put("role", "user");
        userMessageNode.put("content", userMessage);

        String requestJson = requestBody.toString();
        log.info("发送到DeepSeek API的请求: {}", requestJson);

        // Updated to use non-deprecated method
        RequestBody body = RequestBody.create(requestJson, MediaType.parse("application/json"));

        Request request = new Request.Builder()
                .url(apiUrl)
                .post(body)
                .addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("Content-Type", "application/json")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                String errorBody = response.body() != null ? response.body().string() : "无响应体";
                log.error("API调用失败: 状态码={}, 响应={}", response.code(), errorBody);
                throw new IOException("API调用失败: " + response.code() + " " + response.message());
            }

            String responseBody = response.body().string();
            log.info("DeepSeek API响应: {}", responseBody);
            
            try {
                JsonNode responseJson = objectMapper.readTree(responseBody);
                log.info("解析的JSON响应: {}", responseJson);
                
                if (!responseJson.has("choices") || responseJson.path("choices").size() == 0) {
                    log.error("API响应中没有choices字段或为空");
                    return "API响应格式错误，没有找到choices字段";
                }
                
                JsonNode messageNode = responseJson.path("choices").path(0).path("message");
                if (!messageNode.has("content")) {
                    log.error("API响应中没有content字段");
                    return "API响应格式错误，没有找到content字段";
                }
                
                String content = messageNode.path("content").asText();
                log.info("提取的AI回复内容: {}", content);
                
                if (content == null || content.isEmpty()) {
                    log.warn("API返回的内容为空");
                    return "抱歉，AI没有返回有效回复。";
                }
                
                return content;
            } catch (Exception e) {
                log.error("解析API响应失败", e);
                log.error("原始响应: {}", responseBody);
                return "解析AI响应时出错: " + e.getMessage();
            }
        } catch (Exception e) {
            log.error("调用API时发生异常", e);
            throw new IOException("调用AI服务失败: " + e.getMessage(), e);
        }
    }
    
    // 删除 getCompletionStream 方法
}